package main

import (
	"context"
	"sync"
	"time"
	"fmt"
)

//为什么需要context?

var wg sync.WaitGroup

func f2(ctx context.Context){
	defer wg.Done()
FORLOOP:
	for{
		fmt.Println("drink coffee")
		time.Sleep(time.Millisecond * 500)
		select {
		case <- ctx.Done():
			break FORLOOP
		default:

		}
	}
}

func f(ctx context.Context){
	defer wg.Done()
	go f2(ctx)
FORLOOP:
	for{
		fmt.Println("drink tea")
		time.Sleep(time.Millisecond * 500)
		select {
		case <- ctx.Done():	// 等待上级通知
			break FORLOOP
		default:

		}
	}
}

func main(){
	ctx, cancel := context.WithCancel(context.Background())	// 传一个父节点
	wg.Add(1)
	go f(ctx)
	time.Sleep(time.Second * 5)
	// 如何通知子goroutine退出
	cancel()	// 通知子goroutine结束
	wg.Wait()

}